package com.xthink.web.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xthink.common.pojo.cards.CardsIMEI;
import com.xthink.common.pojo.cards.OperationHistory;
import com.xthink.common.result.AjaxResult;
import com.xthink.common.pojo.cards.Cards;
import com.xthink.common.pojo.user.User;
import com.xthink.common.utils.RedisCache;
import com.xthink.common.utils.TranSidUtils;
import com.xthink.common.vo.cards.CardsDetailsVo;
import com.xthink.common.vo.cards.CardsListVo;
import com.xthink.common.vo.cards.UpdateEquipmentRemarksVo;
import com.xthink.common.vo.pool.PoolCardListVo;
import com.xthink.common.vo.user.UserListCardsVo;
import com.xthink.web.mapper.CardsIMEIMapper;
import com.xthink.web.mapper.CardsMapper;
import com.xthink.web.mapper.OperationHistoryMapper;
import com.xthink.web.mapper.UserMapper;
import com.xthink.web.service.CardsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class CardsServiceImpl extends ServiceImpl<CardsMapper, Cards> implements CardsService {

    @Autowired
    private CardsMapper cardsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CardsIMEIMapper cardsIMEIMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private OperationHistoryMapper operationHistoryMapper;

    private final static ObjectMapper mapper = new ObjectMapper();

    @Override
    public AjaxResult likeList(CardsListVo cardsListVo) {
        //模糊查询  条件封装
        LambdaQueryWrapper<Cards> wrapper = new LambdaQueryWrapper<>();
        Page<Cards> cardsPage = new Page<>(cardsListVo.getPage(), cardsListVo.getSize());
        //iccId
        wrapper.like(StringUtils.isNotBlank(cardsListVo.getIccId()), Cards::getIccId, cardsListVo.getIccId());
        //卡号
        //wrapper.like(StringUtils.isNotBlank(cardsListVo.getIccId()), Cards::getCardNumber, cardsListVo.getIccId());
        //状态
        wrapper.eq(cardsListVo.getCardsStatus() != null, Cards::getCardsStatus, cardsListVo.getCardsStatus());


        Page<Cards> cardsPage1 = cardsMapper.selectPage(cardsPage, wrapper);
        List<Cards> records = cardsPage1.getRecords();


        if (records.size() == 0) {
            return AjaxResult.error("未找到此卡");
        }

        return AjaxResult.success("查询成功", records);
    }


    //卡片详情
    @Override
    public AjaxResult cardDetails(String iccId) {
        LambdaQueryWrapper<Cards> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cards::getIccId, iccId);
        Cards cards = cardsMapper.selectOne(wrapper);
        CardsDetailsVo cardsDetailsVo = new CardsDetailsVo();
        BeanUtils.copyProperties(cards, cardsDetailsVo);

        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getId, cardsDetailsVo.getUserId());
        User user = userMapper.selectOne(userWrapper);

        String businessName = user.getBusinessName();
        if (!StringUtils.isNotBlank(businessName)) {
            businessName = "-";
        }
        cardsDetailsVo.setBusinessName(businessName);

        return AjaxResult.success(cardsDetailsVo);
    }

    //绑定池卡片&&卡片搜素
    @Override
    public AjaxResult poolCardList(PoolCardListVo poolCardListVo) {

        Page<Cards> cardsPage = new Page<>(poolCardListVo.getPage(), poolCardListVo.getSize());
        LambdaQueryWrapper<Cards> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(
                StringUtils.isNotBlank(poolCardListVo.getStartIccId()) || StringUtils.isNotBlank(poolCardListVo.getEndIccId())
                , Cards::getIccId
                , poolCardListVo.getStartIccId()
                , poolCardListVo.getEndIccId()
        );

        wrapper.eq(StringUtils.isNotBlank(poolCardListVo.getStatus()), Cards::getCardsStatus, poolCardListVo.getStatus());
        wrapper.eq(Cards::getPoolId, 0);
        Page<Cards> cardsPage1 = cardsMapper.selectPage(cardsPage, wrapper);
        List<Cards> records = cardsPage1.getRecords();
        if (records.size() == 0) {
            return AjaxResult.error("未找到此卡片，可能已经绑定到流量池中");
        }
        return AjaxResult.success(records);
    }

    //解绑池卡片回显
    @Override
    public AjaxResult deletePoolGroupTotal(PoolCardListVo poolCardListVo) {
        Page<Cards> cardsPage = new Page<>(poolCardListVo.getPage(), poolCardListVo.getSize());
        LambdaQueryWrapper<Cards> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(
                StringUtils.isNotBlank(poolCardListVo.getStartIccId()) || StringUtils.isNotBlank(poolCardListVo.getEndIccId())
                , Cards::getIccId
                , poolCardListVo.getStartIccId()
                , poolCardListVo.getEndIccId()
        );

        wrapper.eq(StringUtils.isNotBlank(poolCardListVo.getStatus()), Cards::getCardsStatus, poolCardListVo.getStatus());
        wrapper.eq(Cards::getPoolId, poolCardListVo.getPoolId());
        Page<Cards> cardsPage1 = cardsMapper.selectPage(cardsPage, wrapper);
        List<Cards> records = cardsPage1.getRecords();
        if (records.size() == 0) {
            return AjaxResult.error("未找到此卡片，可能已经解绑");
        }
        return AjaxResult.success(records);
    }


    //经销商内部查看卡片
    @Override
    public AjaxResult userListCards(UserListCardsVo userListCardsVo) {
        LambdaQueryWrapper<Cards> cardsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<Cards> page = new Page<>(userListCardsVo.getPage(), userListCardsVo.getSize());
        cardsLambdaQueryWrapper.like(
                StringUtils.isNotBlank(userListCardsVo.getCardNumber())
                , Cards::getCardNumber
                , userListCardsVo.getCardNumber()
        );

        cardsLambdaQueryWrapper.like(
                StringUtils.isNotBlank(userListCardsVo.getIccId())
                , Cards::getIccId
                , userListCardsVo.getIccId()
        );

        cardsLambdaQueryWrapper.like(
                StringUtils.isNotBlank(userListCardsVo.getBusinessName())
                , Cards::getBusinessName
                , userListCardsVo.getBusinessName()
        );

        cardsLambdaQueryWrapper.eq(
                StringUtils.isNotBlank(userListCardsVo.getOperator())
                , Cards::getOperator
                , userListCardsVo.getOperator()
        );

        cardsLambdaQueryWrapper.eq(
                StringUtils.isNotBlank(userListCardsVo.getStatus())
                , Cards::getCardsStatus
                , userListCardsVo.getStatus()
        );

        if (userListCardsVo.getAssignmentStatus() == 1) {
            cardsLambdaQueryWrapper.eq(
                    Cards::getAssignmentStatus, 0
            );
        }

        Page<Cards> page1 = cardsMapper.selectPage(page, cardsLambdaQueryWrapper);
        List<Cards> records = page1.getRecords();
        if (records.size() == 0) {
            return AjaxResult.error("未查询到此卡片");
        }
        return AjaxResult.success();
    }

    //批量调拨
    @Override
    public AjaxResult binDingUser(Integer[] ids, String businessName) {
        for (Integer id : ids) {
            LambdaUpdateWrapper<Cards> cardsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getBusinessName, businessName);
            User user = userMapper.selectOne(userLambdaQueryWrapper);
            cardsLambdaUpdateWrapper.eq(Cards::getId, id)
                    .set(Cards::getName, user.getName())
                    .set(Cards::getBusinessName, businessName)
                    .set(Cards::getUserId, user.getId())
                    .set(Cards::getAssignmentStatus, 1);
            int update = cardsMapper.update(null, cardsLambdaUpdateWrapper);
            if (update == 0) {
                return AjaxResult.error("卡片ID:" + id + "调拨至" + businessName + "经销商失败");
            }
        }
        return AjaxResult.success();
    }

    //批量解绑
    @Override
    public AjaxResult unBinDingUser(Integer[] ids) {
        for (Integer id : ids) {
            LambdaUpdateWrapper<Cards> cardsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            cardsLambdaUpdateWrapper.eq(Cards::getId, id)
                    .set(Cards::getBusinessName, "-")
                    .set(Cards::getName, "-")
                    .set(Cards::getUserId, 0)
                    .set(Cards::getAssignmentStatus, 0);
            int update = cardsMapper.update(null, cardsLambdaUpdateWrapper);
            if (update == 0) {
                return AjaxResult.error("卡片ID:" + id + "解绑失败");
            }
        }
        return AjaxResult.success();
    }


    @Override
    public AjaxResult updateEquipmentRemarks(UpdateEquipmentRemarksVo updateEquipmentRemarksVo) {
        LambdaUpdateWrapper<Cards> cardsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        cardsLambdaUpdateWrapper.eq(Cards::getId, updateEquipmentRemarksVo.getCardId());

        cardsLambdaUpdateWrapper.set(
                StringUtils.isNotBlank(updateEquipmentRemarksVo.getEquipment())
                , Cards::getEquipment
                , updateEquipmentRemarksVo.getEquipment()
        );

        cardsLambdaUpdateWrapper.set(
                StringUtils.isNotBlank(updateEquipmentRemarksVo.getRemarks())
                , Cards::getRemarks
                , updateEquipmentRemarksVo.getRemarks()
        );

        int update = cardsMapper.update(null, cardsLambdaUpdateWrapper);
        if (update == 0) {
            return AjaxResult.error("修改信息失败");
        }

        //记录管理员操作内容
        OperationHistory operationHistory = new OperationHistory();
        operationHistory.setCardId(updateEquipmentRemarksVo.getCardId());
        operationHistory.setName(redisCache.getCacheObject("adminName"));
        if (StringUtils.isNotBlank(updateEquipmentRemarksVo.getEquipment())){
            operationHistory.setRecord("编辑关联设备操作");
        }

        if (StringUtils.isNotBlank(updateEquipmentRemarksVo.getRemarks())){
            operationHistory.setRecord("编辑备注操作");
        }

        operationHistoryMapper.insert(operationHistory);

        return AjaxResult.success();
    }

    //获取IMEI
    @Override
    public AjaxResult getIMEI(Integer id) {

        Cards cards = cardsMapper.selectById(id);
        String iccId = cards.getIccId();

        HttpRequest request =
                HttpRequest
                        .get("https://api.iot.10086.cn/v5/ec/query/sim-imei?transid="+ TranSidUtils.getTranSid()+"&token="+redisCache.getCacheObject("token")+"&iccid="+iccId);
        HttpResponse response = request.execute();
        String body = response.body();
        try {

            JsonNode jsonNode = mapper.readTree(body);
            if (ObjectUtils.isNull(jsonNode.get("result"))){
                int status = jsonNode.get("status").asInt();
                String message = jsonNode.get("message").asText();
                return AjaxResult.error(status,message);
            }else {
                String imei = jsonNode.get("result").get("imei").asText();
                //修改最新的IMEI
                LambdaUpdateWrapper<Cards> cardsLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                cardsLambdaUpdateWrapper.eq(Cards::getId,id).set(Cards::getIMEI,imei);
                cardsMapper.update(null,cardsLambdaUpdateWrapper);
                //存入历史记录
                CardsIMEI cardsIMEI = new CardsIMEI();
                cardsIMEI.setCardId(id);
                cardsIMEI.setIMEI(imei);
                cardsIMEIMapper.insert(cardsIMEI);
            }

        } catch (JsonProcessingException e) {
            log.error(String.format("获取结果失败：%s",e.getMessage()));
            e.printStackTrace();
        }

        //记录管理员操作内容
        OperationHistory operationHistory = new OperationHistory();
        operationHistory.setCardId(id);
        operationHistory.setName(redisCache.getCacheObject("adminName"));
        operationHistory.setRecord("获取IMEI信息操作");
        operationHistoryMapper.insert(operationHistory);
        return AjaxResult.success();
    }

}
